package com.aishang.javacv.lab.jobs;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.OpenCVFrameConverter;

/**
 * 线程任务，rtmp流录制为ts文件
 */
@Slf4j
@Data
@AllArgsConstructor
public class VideoPusher implements Runnable{
    //rtmp地址
    private String from;
    //目标地址,ts文件储存位置
    private String to;
    //线程结束标识
    private boolean exit = false;

    @Override
    public void run() {
        // 使用rtsp的时候需要使用 FFmpegFrameGrabber，不能再用 FrameGrabber
        try {
            int width = 640,height = 480;
            FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(from);
            // 使用tcp的方式，不然会丢包很严重
            grabber.setOption("rtmp_transport", "tcp");
            grabber.setImageWidth(width);
            grabber.setImageHeight(height);
            log.info("grabber start");
            grabber.start();
            // 流媒体输出地址，分辨率（长，高），是否录制音频（0:不录制/1:录制）
            FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(to,width,height, 0);
            recorder.setInterleaved(true);
            //recorder.setVideoOption("crf","28");
            // 28
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
            // rtsp的类型
            recorder.setFormat("ts");
            recorder.setFrameRate(25);
            recorder.setImageWidth(width);recorder.setImageHeight(height);
            // yuv420p
            recorder.setPixelFormat(0);
            log.info("recorder start");
            recorder.start();
            //
            OpenCVFrameConverter.ToIplImage conveter = new OpenCVFrameConverter.ToIplImage();
            log.info("all start!!");
            int count = 0;
            while(!exit){
                count++;
                Frame frame = grabber.grabImage();
                if(frame == null){
                    continue;
                }
                if(count % 100 == 0){
                    log.info("count="+count);
                }
                recorder.record(frame);
            }

            grabber.stop();
            grabber.release();
            recorder.stop();
            recorder.release();
            log.info("推流结束=======================");
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
